<?php
namespace app\modules\supplier\logic;
use app\modules\base\LogicBase;
use think\Db;
use app\modules\supplier\traits\ParseSupplierOrders;
use app\modules\supplier\traits\ParseOrderGoods;
use Barcodegen\Barcode;
/**
 *
 */

class OrdersLogic extends LogicBase
{
    use ParseSupplierOrders;
    use ParseOrderGoods;
    public function _initialize()
    {

    }

    /**
     * 订单列表
     * @param int $supplier_id 供应商ID
     * @param array $_option 数组
     * @return bool|array
     */

    public function index($supplier_id,$_option=[]){

        if ( empty($supplier_id) || !Db::name('supplier')->where(['supplier_id'=>$supplier_id])->find() ){
            $this->_error[] ='供应商不存在！';
            return false;
        }

        $option = [
            'is_pages' => false,//是否分页查询
            'page_current' => 10,//分页查询时，当前页码
            'page_size' => 1,
            'keyword' => '',
            'order' => 'DESC',
            'sort' => 'create_time'
        ];

        if (is_array($_option)) {
            if (isset($_option['is_pages'])) {
                $option['is_pages'] = $_option['is_pages'] ? true : false;
            }
            if (isset($_option['page_current'])) {
                $option['page_current'] = intval($_option['page_current']);
                $option['page_current'] = $option['page_current'] < 1 ? 1 : $option['page_current'];
            }
            if (isset($_option['page_size'])) {
                $option['page_size'] = intval($_option['page_size']);
                $option['page_size'] = $option['page_size'] < 1 ? 1 : $option['page_size'];
            }
            if (isset($_option['field'])) {
                $option['field'] = strip_tags(trim($_option['field']));
                $option['field'] = $option['field'] == 'all' ? '*' : $option['field'];
            }

            if (isset($_option['sort'])) {
                $option['sort'] = strip_tags(trim($_option['sort']));
                if (empty($option['sort'])) {
                    $option['sort'] = "create_time";
                }
            }
            if (isset($_option['order'])) {
                $option['order'] = strip_tags(trim($_option['order']));
            }

            //筛选条件
            if (isset($_option['keyword'])) {
                $option['keyword'] = strip_tags(trim($_option['keyword']));
            }

            if (isset($_option['order_status'])){
                $option['order_status'] = is_numeric($_option['order_status'])?intval($_option['order_status']):$_option['order_status'];
            }
        }

        $where =['supplier_id'=>$supplier_id];

        if($option['order_status'] !== ''){
            if ($option['order_status'] == 40 || $option['order_status']==60){
                $where['order_status'] = ['IN',[40,60]];
            }else{
                $where['order_status'] = $option['order_status'];
            }
        }

        if (!empty($option['keyword'])){
            $where['order_no'] = ['like', '%' . str_replace('%', '\%', $option['keyword']) . '%'];
        }

        if ($option['is_pages']) {
            $data['record_count'] = Db::name('supplier_order')
                ->where($where)
                ->count();
            $data['page_size'] = $option['page_size'];
            $data['page_max'] = ceil($data['record_count'] / $option['page_size']);
            $data['page_current'] = $option['page_current'];
            $data['list'] =  Db::name('supplier_order')
                ->where($where)
                ->order($option['sort'].' '.$option['order'])
                ->page($option['page_current'], $option['page_size'])->
                select();
        }else{
            $data['record_count'] = Db::name('supplier_order')
                ->where($where)
                ->count();
            $data['page_size'] = $option['page_size'];
            $data['page_max'] = ceil($data['record_count'] / $option['page_size']);
            $data['page_current'] = $option['page_current'];
            $data['list'] =  Db::name('supplier_order')
                ->where($where)
                ->order($option['sort'].' '.$option['order'])
                ->limit($option['page_size'])->
                select();
        }

//        echo Db::name('supplier_order')->getLastSql();exit();

        foreach ($data['list'] as $key => $val){
            $data['list'][$key] = $this->_parseSupplierOrders($val);//格式化
            //获取订单产品
            $data['list'][$key]['order_goods'] = Db::name('order_goods')
                ->where(['order_id'=>$val['order_id']])
                ->select();
            foreach ($data['list'][$key]['order_goods'] as $k =>$v){
                $data['list'][$key]['order_goods'][$k] = $this->_parseOrderGoods($v);//格式化
            }
        }

//        echo Db::name('goods')->getLastSql();exit();

        return $data;

    }


    /**
     * 订单详情
     * @param integer $oid 订单ID
     * @return bool|array
     */
    public function get($oid = 0){

        if (empty(get_supplier_id()) || !Db::name('supplier')->where(['supplier_id'=>get_supplier_id()])->find()){
            $this->_error[]='无效参数';
            return false;
        }

        if (empty($oid) || !Db::name('supplier_order')->where(['oid'=>$oid])->find()){
            $this->_error[] ='无效参数';
            return false;
        }

        $where =['oid'=>$oid];
        //商品详情数据
        $data['order'] = Db::name('supplier_order')
            ->where($where)
            ->find();

        $data['order'] = $this->_parseSupplierOrders($data['order']);

        //获取商品规格基础数据
        $data['order_goods'] = Db::name('order_goods')->alias('OG')
            ->join('goods_specval GS','OG.goods_specval_id = GS.specval_id','LEFT')
            ->where(['OG.order_id'=>$data['order']['order_id'],'GS.status'=>1])
            ->select();

        //'GS.specval_pid'=>['<>',0] 注释 剔除筛选条件原因 取消订单，缺货，

        foreach ($data['order_goods'] as $key =>$val){
            $data['order_goods'][$key] = $this->_parseOrderGoods($val);
        }

        return $data;

    }

    /**
     * 打印条码
     * @param integer $oid 订单ID
     * @return bool|array
     */
    public function PrintBrcode($oid){
        vendor('Barcodegen.Barcode');
        $Barcode = new Barcode();

        if (empty(get_supplier_id()) || !Db::name('supplier')->where(['supplier_id'=>get_supplier_id()])->find()){
            $this->_error[]='无效参数';
            return false;
        }

        if (empty($oid) || !Db::name('supplier_order')->where(['oid'=>$oid])->find()){
            $this->_error[] ='无效参数';
            return false;
        }

        $where =['oid'=>$oid];
        //商品详情数据
        $info = Db::name('supplier_order')
            ->where($where)
            ->find();

        //获取商品规格基础数据
        $data = Db::name('order_goods')->alias('OG')
            ->join('goods_specval GS','OG.goods_specval_id = GS.specval_id','LEFT')
            ->where(['OG.order_id'=>$info['order_id'],'GS.status'=>1])
            ->select();
          //'GS.specval_pid'=>['<>',0] 注释 剔除筛选条件原因 取消订单，缺货，

        foreach ($data as $key =>$val){

            $data[$key] = $this->_parseOrderGoods($val);
            //检测是否生成brcode
            if (empty($val['brcode'])){
                $brcode = $Barcode->draw(sprintf('%08s',$info['order_id'].'-'.$val['specval_id']))->save('apiUploads/attachment/brcode/su'.get_supplier_id().'/');
                $res = Db::name('goods_specval')->where(['specval_id'=>$val['specval_id']])->setField('brcode','/'.$brcode);
                if ($res!==false){
                    $data[$key]['brcode'] = '/'.$brcode;//强制更新数组
                }
            }
        }
        return $data;
    }

    /**
     * 订单状态
     * @param integer $oid 订单ID
     * @param integer $order_status
     * @return bool|array
     */
    public function OrderStatusChange($oid,$order_status){
        if (empty(get_supplier_id()) || !Db::name('supplier')->where(['supplier_id'=>get_supplier_id()])->find()){
            $this->_error[]='无效参数';
            return false;
        }

        if (empty($oid) || !Db::name('supplier_order')->where(['oid'=>$oid])->find()){
            $this->_error[] ='无效参数';
            return false;
        }

        if (Db::name('supplier_order')->where(['oid'=>$oid,'order_status'=>$order_status])->find()){
            $this->_error[]='已经改变订单状态无需重复操作';
            return false;
        }

        if (Db::name('supplier_order')->where(['oid'=>$oid,'order_status'=>10])->find()){
            $this->_error[]='订单已经被取消！';
            return false;
        }

        Db::startTrans();//开启事务
        $order_info = Db::name('supplier_order')->where(['oid'=>$oid])->find();//订单详情
        $order_goods =  Db::name('order_goods')->where(['order_id'=>$order_info['order_id'],'supplier_id'=>get_supplier_id()])->select();//订单商品
        if(empty($order_goods)){
            $this->_error[] ='订单商品不存在！';
            return false;
        }
        $res = false;
        $res_2 =false;
        switch ($order_status){
            case 10: //取消  1.减少对应速冻在线的规格库存 2.更新订单商品表的规格ID

                foreach ($order_goods as $key => $val){
                    $specval_id = Db::name('goods_specval')->where(['specval_id'=>$val['goods_specval_id'],'supplier_id'=>get_supplier_id()])->value('specval_pid');
                    if (empty($specval_id)){
                        $this->_error[]='【'.$val['goods_name'].'】对应基础规格不存在！';
                        return false;
                    }
                    $res = Db::name('goods_specval')->where(['specval_id'=>$specval_id])->setDec('stock',$val['num']);//减速冻在线规格库存
                    $res_2 = Db::name('order_goods')->where(['order_goods_id'=>$val['order_goods_id'],'order_id'=>$order_info['order_id'],'supplier_id'=>get_supplier_id()])->setField('goods_specval_id',$specval_id);
                }
                break;
            case 40: //接单待出货 (new下单时不减预采购数量，接单时无需加数量)
//                $order_goods =  Db::name('order_goods')->field('goods_specval_id,num')->where(['order_id'=>$order_info['order_id'],'supplier_id'=>get_supplier_id()])->select();
//                foreach ($order_goods as $key =>$val){
//                    $res = Db::name('goods_specval')->where(['specval_id'=>$val['goods_specval_id'],'supplier_id'=>get_supplier_id()])->setInc('stock',$val['num']);
//                }
                $res = true;
                $res_2 = true;
                break;
            case 60: //出货中
                   $res = true;
                   $res_2 = true;
                break;
//            case 100://完成 操作 采购表 insert（new）
//
//                $order_goods =  Db::name('order_goods')->alias('OG')
//                    ->field('OG.*,GS.purchase_price,GS.price as s_price')
//                    ->join('goods_specval GS','OG.goods_specval_id = GS.specval_id','LEFT')
//                    ->where(['OG.order_id'=>$order_info['order_id'],'OG.supplier_id'=>get_supplier_id()])
//                    ->select();
//                foreach ($order_goods as $key =>$val){
//                    $data['goods_id'] = $val['goods_id'];
//                    $data['specval_id'] = $val['goods_specval_id'];
//                    $data['specval_name'] = $val['goods_specval_name'];
//                    $data['spec_name'] = $val['goods_spec_name'];
//                    $data['goods_name'] = $val['goods_name'];
//                    $data['picture'] = $val['goods_picture'];
//                    $data['num'] = $val['num'];
//                    $data['last_price'] = $val['purchase_price'];
//                    $data['price'] = $val['s_price'];
//                    $data['pay_status'] = 1;
//                    $data['create_time']  =date('Y-m-d H:i:s');
//                    $data['purchase_id'] = 0;
//                    $data['supplier_id'] = $val['supplier_id'];
//                    $data['brand_id'] = $val['brand_id'];
//                    $data['brand_name'] = $val['brand_name'];
//
//                    $res = Db::name('purchase_goods')->insert($data);
//
//                }
//                break;
            default:
                $this->_error[] ='提交状态有误！';
                return false;
                break;
        }

        $res_1 = Db::name('supplier_order')->where(['oid'=>$oid])->setField('order_status',$order_status);

        if ($res!==false  && $res_2!==false && $res_1!== false){
            Db::commit();
            return true;
        }else{
            Db::rollback();
            return false;
        }
    }

    /**
     * 订单商品状态
     * @param integer $order_goods_id 订单ID
     * @param integer $status 订单商品状态
     * * @param integer $num  缺货数量
     * @return bool|array
     */
    public function OrderGoodsStatusChange($order_goods_id,$status,$num){

        if (empty(get_supplier_id()) || !Db::name('supplier')->where(['supplier_id'=>get_supplier_id()])->find()){
            $this->_error[]='无效参数';
            return false;
        }

        if (empty($order_goods_id) || !Db::name('order_goods')->where(['order_goods_id'=>$order_goods_id])->find()){
            $this->_error[] ='无效参数';
            return false;
        }

        //  1.减少对应速冻在线的规格库存 2.拆分订单商品 3. 标识订单商品状态

        if (Db::name('order_goods')->where(['order_goods_id'=>$order_goods_id,'status'=>$status])->find()){
            $this->_error[]='已经改变订单状态无需重复操作';
            return false;
        }

        if(empty($num)){
            $this->_error[] ='请填写缺货数量！';
            return false;
        }

        Db::startTrans();//开启事务


        $order_goods =  Db::name('order_goods')->where(['order_goods_id'=>$order_goods_id,'supplier_id'=>get_supplier_id()])->find();//订单商品


        $specval_id = Db::name('goods_specval')->where(['specval_id'=>$order_goods['goods_specval_id'],'supplier_id'=>get_supplier_id()])->value('specval_pid');

        if (empty($specval_id)){
            $this->_error[]='【'.$order_goods['goods_name'].'】对应基础规格不存在！';
            return false;
        }

        $res = Db::name('goods_specval')->where(['specval_id'=>$specval_id])->setDec('stock',$num);//减速冻在线规格库存


        $res_2 = false;
        $res_3 = false;
        if ($num < $order_goods['num']){ //缺货数量小于订单数量 拆分订单

            //订单拆分
            $data = $order_goods;
            unset($data['order_goods_id']);//去除主键
            $data['goods_specval_id'] = $specval_id;//拆分订单 基础规格
            $data['num'] = $num;//生成数量
            $res_2 = Db::name('order_goods')->insert($data);

            //修改拆分后数量

            $res_3 = Db::name('order_goods')->where(['order_goods_id'=>$order_goods_id,'supplier_id'=>get_supplier_id()])->setField('num',$order_goods['num'] - $num);

        }elseif($num == $order_goods['num']){//此规格全部缺货 更新规格ID

            $res_2 = Db::name('order_goods')->where(['order_goods_id'=>$order_goods_id,'supplier_id'=>get_supplier_id()])->setField('goods_specval_id',$specval_id);
            $res_3 = true;

        }elseif($num > $order_goods['num']){// 填写不规范
            $this->_error[] ='请正确填写缺货数量，不能大于订单商品数量';
            return false;
        }

        //修改状态
        $res_4 = Db::name('order_goods')->where(['order_goods_id'=>$order_goods_id,'supplier_id'=>get_supplier_id()])->setField('status',$status);

        if ($res!== false && $res_2!==false && $res_3!==false && $res_4!==false){
            Db::commit();
            return true;
        }else{
            Db::rollback();
            return false;
        }

    }



}